package com.swak.nio_udp.unicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import com.swak.utils.Nets;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * 使用单播来通讯
 * 
 * @author 618lf
 */
@Getter
@Setter
@Accessors(chain = true)
public class Peer {

	private DatagramSocket socket = null;
	private int port;
	private Thread loop;

	public Peer(int port) throws SocketException, UnknownHostException {
		this.socket = new DatagramSocket(port, Nets.getLocalAddress());
		this.loop = new Thread(this::receive);
		this.loop.setDaemon(false);
		this.loop.start();
	}

	private void receive() {
		while (true) {
			try {
				byte[] recvBuffer = new byte[1024];
				final DatagramPacket recvPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
				this.socket.receive(recvPacket);
				System.out.println("received packet from " + recvPacket.getAddress().getHostAddress() + " : "
						+ recvPacket.getPort());
				// 注意由于DatagramPacket的缓冲区复用，本次收到的最后一个字符后并不会补'\0',而是使用一个长度标记
				String msg = new String(recvPacket.getData(), recvPacket.getOffset(), recvPacket.getLength());
				System.out.println("received " + msg);
			} catch (Exception e) {
			}
		}
	}

	public void send(InetAddress addr, int port, String message) throws IOException {
		byte[] buffer = message.getBytes();
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
		packet.setAddress(addr);
		packet.setPort(port);
		socket.send(packet);
	}
}